package com.cy.train.member.service.imp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.cy.train.common.req.MemberTicketReq;
import com.cy.train.common.resp.PageResp;
import com.cy.train.common.util.SnowUtil;
import com.cy.train.member.domain.Ticket;
import com.cy.train.member.domain.TicketExample;
import com.cy.train.member.mapper.TicketMapper;
import com.cy.train.member.req.TicketQueryReq;
import com.cy.train.member.resp.TicketQueryResp;
import com.cy.train.member.service.TicketService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Date: 2024/2/27 14:48
 * @Author: cyzhang
 */
@Service
public class TicketServiceImp implements TicketService {
    private static final Logger LOG = LoggerFactory.getLogger(TicketServiceImp.class);

    @Autowired
    private TicketMapper ticketMapper;

    @Override
    public void save(MemberTicketReq req) {
        LOG.info("seata全局事务ID：{}", RootContext.getXID());
        DateTime now = DateTime.now();
        Ticket ticket = BeanUtil.copyProperties(req, Ticket.class);
        ticket.setId(SnowUtil.getSnowflakeNextId());
        ticket.setCreateTime(now);
        ticket.setUpdateTime(now);
        ticketMapper.insert(ticket);
    }

    @Override
    public PageResp<TicketQueryResp> queryList(TicketQueryReq req) {
        TicketExample ticketExample = new TicketExample();
        ticketExample.setOrderByClause("id desc");

        LOG.info("当前页：{}", req.getPage());
        LOG.info("每页数量：{}", req.getSize());

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ticket> ticketList = ticketMapper.selectByExample(ticketExample);

        PageInfo<Ticket> pageInfo = new PageInfo<>(ticketList);
        LOG.info("总条数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<TicketQueryResp> ticketQueryRespList = BeanUtil.copyToList(ticketList, TicketQueryResp.class);
        PageResp<TicketQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(ticketQueryRespList);

        return pageResp;
    }

    @Override
    public void delete(Long id) {
        ticketMapper.deleteByPrimaryKey(id);
    }
}
